<?php 
class ForumController extends DomController {

	public function index() {
		
		$view = new DomView('Forum/tree.html',60,'forumTree');
		if( !$view->isCached() ) {
			
			$threads = ForumThread::dataQuery()->select('t.id, t.name, 0 as level')->where('t.thread <=> NULL')->commit();
			$list = array();
			foreach( $threads as $thread ) {
				$list[] = $thread;
				$sub = ForumThread::dataQuery()
					->select('t.id, t.name, t.description, 1 as level, t.views, t.nrOfPosts, t.lastTopicTitle, t.lastPostTime, t.lastPostUser, t.lastPostUserNickname as lastPostNickname')
					->where('t.thread = '.$thread['id'].'')
					->orderBy('t.id');
				foreach( $sub as $t ) {
					$list[] = $t;
				}
			}
			$view->threads = $list;
			
			$marketView = new DomView('/Market/Market/itemsLine.html');
			$items = MarketItemsSearchQuery::c()
				->onlyPublic()
				->limit(18)
				->orderBy('t.datetime DESC')
				->commit()->toArray();
			$marketView->items = $items;
			$view->marketItems = $marketView->fetch();
		}
		
		$this->view->smartAddAllowed = true;
		
		$this->view->contents = $view->fetch();
		
	}
	
	public function thread( $id ) {
		DomSql::query('UPDATE forum_threads SET views = views+1 WHERE id = '.(int)$id.' LIMIT 1');
	
		$user = BuduaarUser::getLoggedInUser('BuduaarUser');
		
		$view = new DomView('Forum/thread.html',0,'thread_'.$id);
		
		if( $view->isCached() == false ) {
			
			$thread  = ForumThread::dataQuery()->select('t.id, t.name, t.allowTopics')->where('t.id = '.(int)$id.'')->limit(1)->commit();
			$view->thread = $thread;
				
			$pager = new DomPager(1,40,$this->getUrl('thread/'.$id));
			
			
			
			$view->threads = ForumThread::dataQuery()
				->select('t.id, t.name, t.description, 1 as level, t.views, t.nrOfPosts, t.lastTopicTitle, t.lastPostTime, t.lastPostUser, t.lastPostUserNickname as lastPostNickname')
				->where('t.thread = '.(int)$id.'')
				->orderBy('t.id')
				->commit();
	
			
			$request = ForumTopic::dataQuery()
				->countFoundRows()
				->select('t.id, t.title, t.lastPostTime, t.icon, t.views, t.nrOfPosts, t.lastPostUserNickname as nickname, UNIX_TIMESTAMP(lastPostTime) as lastPostStamp, u.username as starterUsername')
				->join('users','u','u.id = t.user')
				->where('t.thread = '.(int)$id.'')
				->orderBy('lastPostTime DESC')
				->limit( $pager->getLimit() )
				->commit();
			
			$pager->setTotal( $request->foundRows() );
				
			$topics = array();
			foreach( $request as $topic ) {
				if( $_GET['allRead'] == 1 ) {$_SESSION['forum_viewd_topics'][$topic['id']] = strtotime('now');}
				$topic['new'] = (bool)($user && $user->lastLogin->stamp() <= $topic['lastPostStamp'] && isset($_SESSION['forum_viewd_topics'][$topic['id']]) && $_SESSION['forum_viewd_topics'][$topic['id']] <= $topic['lastPostStamp']);
				$topic['lk'] = ceil($topic['nrOfPosts']/40)-1;
				$topic['lk'] = $topic['lk'] < 0 ? 0 : $topic['lk'];
				$topics[] = $topic;
			}
			$view->topics = $topics;
			$view->nextLink = $pager->getNextLink();
			$view->prevLink = $pager->getPrevLink();
			$view->pages = $pager->getPages();
			$view->location = $this->getPathHtml( $id );
			
			
		}
		
		$this->view->contents = $view->fetch();
		$this->view->title = 'Buduaari foorum - '.$thread['name'];
		$this->view->description = 'Buduaari foorumi: '.$thread['name'];
		$this->view->keywords = 'Buduaar, Foorum, Teema, '.$thread['name'];
	}
	
	public function topic( $id ) {
		
		DomSql::query('UPDATE forum_topics SET views = views+1 WHERE id = '.(int)$id.' LIMIT 1');
		$_SESSION['forum_viewd_topics'][$id] = strtotime('now');
		
		$user = BuduaarUser::getLoggedInUser('BuduaarUser');
		
		$view = new DomView('Forum/topic.html');
		
		$pager = new DomPager(1,40,$this->getUrl('topic/'.$id));
		
		
		$topic = ForumTopic::dataQuery()
			->select('t.thread, t.id, t.title, t.contents, t.nrOfImages, u.id as userId, u.username, u.nickname, u.posts as posts, u.icon as userIcon, DATE_FORMAT(time,\'%d-%m-%Y %H:%i\') as date ')
			->join('users','u','t.user = u.id')
			->where('t.id = '.(int)$id.'')
			->limit(1)
			->commit();
		
		$result = ForumPost::dataQuery()
			->countFoundRows()
			->select(' t.id, t.title, t.contents, t.nrOfImages, u.id as userId, u.username, u.nickname, u.posts as posts, u.icon as userIcon, DATE_FORMAT(time,\'%d-%m-%Y %H:%i\') as date ')
			->join('users','u','t.user = u.id')
			->where('t.topic = '.(int)$id.'')
			->orderBy('t.time')
			->limit( $pager->getLimit() )
			->commit();
		
		
		$pager->setTotal( $result->foundRows() );

		$posts = array();
		foreach( array_merge(array($topic),$result->toArray()) as $i => $post ) {
			ForumPostBase::parsePost( $post['contents'] );
			$post['images'] = array();
			$post['contents'] = nl2br($post['contents']);
			if( $post['nrOfImages'] > 0 ) {
				$post['images'] = ForumImage::dataQuery()->select('t.id, t.title, t.icon, t.image')->where( ($i==0 ? 'topic=' : 'post=' ).$post['id'] );
			}

			if( $post['userId'] > 0 && ($post['userId'] == $user->id or $user && $user->rights->isAllowed('forum')) ) {
				$post['allowModify'] = true;
			}
			$posts[] = $post;
		}
		
		
		
		$view->loggedInUser = $user;
		$view->posts = $posts;
		$view->nextLink = $pager->getNextLink();
		$view->prevLink = $pager->getPrevLink();
		$view->pages = $pager->getPages();
		$view->location = $this->getPathHtml( $posts[0]['thread'] );
		
		$this->view->contents = $view->fetch();
		
		$this->view->title = 'Buduaari foorum - '.$posts[0]['title'];
		$this->view->description = 'Buduaari foorumi: '.$posts[0]['title'];
		$this->view->keywords = 'Buduaar, Foorum, Teema';
	}
	
	public function delete( $what, $id ) {
		$user = BuduaarUser::getLoggedInUser('BuduaarUser');
		if( $what == 'post' ) {
			$post = DomAr::load( $id, 'ForumPost' );
			$section = 'topic/' . $post->topic->id;
		} else {
			$post = DomAr::load( $id, 'ForumTopic' );
			$section = 'thread/' . $post->thread->id;
		}
			
		if( $post->user->id == $user->id or $user && $user->rights->isAllowed('forum')  )
			$post->delete();
		
		$this->goToSection($section);
	}

	/**
	* @param Int $id Depending on action parent thread or parent topic id or post/topic id that will be changed.
	* @param String $action ["addTopic" - to add new topic, id must be thread id, "addPost" - to add new post, id must be topic id, NULL - to change topic or post. Id must be topic or post id.]
	* @param Int $id Postituse id millest tehakse tsitaat.
	*/
	public function managePost(  $id = NULL, $action = NULL, $tsitId = NULL) {
		
		
		$user = BuduaarUser::getLoggedInUser('BuduaarUser');
		
		if( !$user ) {
			$this->view->contents = "<h2>Selleks, et postitada peate sisse logima!</h2>";
			return;
		}
		
		switch( $action ) {
			case 'addTopic':

				if( in_array($id, array(19,20,21,22,23,24,25)) ) {
					$this->view->contents  = '<h2>Kategooria on suletud! Postituste lisamine ei ole lubatud!</h2> <br> Uus buduaari turg asub aadressil <a class="red" href="http://buduaar.ee/Turg/">http://buduaar.ee/Turg/</a>';
					return;
				}
						
				$thread = ForumThread::load( $id );
				$post = $_SESSION['lastForumPost'][$id] ? ForumTopic::unserialize($_SESSION['lastForumPost'][$id]) : new ForumTopic();
				$topic = $post;
				$thread->topics[] = $topic;
				$post->user = $user;
			break;
			case 'addPost':
				$topic = ForumTopic::load( $id );
				$thread = $topic->thread;
						
				if( in_array($thread->id, array(19,20,21,22,23,24,25)) ) {
					$this->view->contents  = '<h2>Kategooria on suletud! Postituste lisamine ei ole lubatud!</h2> <br> Uus buduaari turg asub aadressil <a class="red" href="http://buduaar.ee/Turg/">http://buduaar.ee/Turg/</a>';
					return;
				}
		
				$post = ForumPost::unserialize($_SESSION['lastForumPost'][$id]);
				if( !$post ) $post = new ForumPost();
				$topic->posts[] = $post;
				$post->user = $user;	
				
				if( substr($tsitId,0,1) == 't' ) 
					$tsit = $tsitId ? '[tsiteeri]'.DomSql::selectOneQuery('SELECT contents FROM forum_topics WHERE id = '.(int)substr($tsitId,1).' LIMIT 1', 'contents').'[/tsiteeri]' : '';		
				else
					$tsit = $tsitId ? '[tsiteeri]'.DomSql::selectOneQuery('SELECT contents FROM forum_posts WHERE id = '.(int)substr($tsitId,1).' LIMIT 1', 'contents').'[/tsiteeri]' : '';
				
			break;
			default:
				if( $action == 'topic')
					$post = DomAr::load( $id, 'ForumTopic' );
				else 
					$post = DomAr::load( $id, 'ForumPost' );
				
				$action = 'changePost';
				$topic = get_class($post) == 'ForumPost' ? $post->topic : $post;
				$thread = $topic->thread;
				$this->view->edit = true;
				
				if( !($user->id == $post->user->id or $user && $user->rights->isAllowed('forum')) ) return;
			break;
		}
		

		
		if( $_POST['addNewImage'] ) {
			$image = new ForumImage();
			$image->title = $_POST['newImageComment'];
			$image->image->addUploaded( $_FILES['newImage']['tmp_name'], $_FILES['newImage']['name'] ); 
			
			if( $image->validated() && $image->image->exists() ) {
				$post->images[] = $image;
			
				
				if( $post->id > 0 ) {
					$post->save();
				}
			} else {
				$this->view->error = implode('<br />', $image->getValidationMessages() );
			}
					
		}

		if( $_POST['deleteImage'] ) {
			
			if( !$post->id ) {
				$rImage = $post->images->getNew( $_POST['deleteImage']-1 );
				if( $rImage ) {
					$post->images->remove( $rImage );
					$rImage->image->unlink();
					$rImage->icon->unlink();
				}
			} else {
				$image = ForumImage::load( $_POST['deleteImage']-1 );
				if( $image )
					$image->delete();
			}	 
		}
		
		if( $_POST ) {
			
			$post->title = htmlspecialchars($_POST['title']);
			$post->sendEmailOnReplay = (bool)$_POST['sendEmailOnReplay'];
			$post->icon->addUploaded( $_FILES['icon']['tmp_name'],$_FILES['icon']['name'] );
			
			$post->contents = htmlspecialchars($_POST['contents']);
			
			if( is_array($_POST['imageComment']) ) {
				foreach( $_POST['imageComment'] as $i => $value ) {
					$image = ForumImage::load( $i );
					if( $image && $image->image->exists() ) {
						$image->title = $value;
						$image->save();
					}
				}
			}
			
			if( $post->validated() && $_POST['forumSave'] ) {
				

				if( $post->id == 0 && get_class($post) == 'ForumPost' ) {

					$lastPost = $topic->posts->query()->limit(1)->orderBy('t.time DESC')->commit();
					if( !$lastPost )
						$lastPost = $topic;
					
					//debug( $lastPost->user->email);
					//debug($user->email);
					//debug($lastPost->sendEmailOnReplay);
					
					if( $lastPost->sendEmailOnReplay == true  && $lastPost->user->email != $user->email && $lastPost->user->email != '' ) {
						$mail = new Mail();	
						$mail->CharSet = 'utf-8';
						$mail->From     = "info@buduaar.ee";
						$mail->FromName = "Buduaar.ee";
						$mail->IsHTML(true); 
						$mail->Subject  =  'Foorumi postitus';
						$mail->Body     =  'Foorumis vastati teemasse '.$topic->title.'! Teema asub <a href="'.$this->getUrl('topic/'.$topic->id).'">SIIN</a> <br /> Sellele kirjale ärge vastake! <br /><br /> Kui te ei saa linki vajutada, siis teema asub siin aadressil: '.$this->getUrl('topicId/'.$topic->id);
						$mail->AltBody  =  'Foorumis vastati teemasse '.$topic->title.'! Link teemale on '.$this->getUrl('topic/'.$topic->id).''."\n".' Sellele kirjale ärge vastake!';
						$mail->AddAddress( $lastPost->user->email );
						$mail->Send();
						//debug('SEND EMAIL');
					}
				}
				
				$post->save();
				unset($_SESSION['lastForumPost'][$id]);
				$this->view->ok = 'Lisatud!';
				$this->goToSection('topic/'.$topic->id);
			} else {
				$this->view->error = implode('<br />', $post->getValidationMessages() );
			}
		}
		
		if( !$user ) {
			$this->view->error  = 'Selleks, et postitada peate sisselogima!';
			$this->view->hideForm = true;
		}
		
		
		$this->view->contents = $tsit . $post->contents;
		$this->view->title = $post->title;
		$this->view->sendEmailOnReplay = $post->sendEmailOnReplay;
		$this->view->topicImage = $post->icon->exists() ? $post->icon->getUrl() : NULL;
		$this->view->images = $post->id ? $post->images->toIdArray() : $post->images->getNewObjects();
		$this->view->editTopic = get_class($post) == 'ForumTopic';
		$this->view->addPartitioner('contents', 'Forum/managePost.html');
		
		if( !$post->id )
			$_SESSION['lastForumPost'][$id] = $post->serialize();
		
	}
	
	private function getPathHtml( $threadId ) {
		
		$view = new  DomView('Forum/location.html',5,'location|id'.(int)$threadId);
		
		if( !$view->isCached() ) {
			
			$list = array();
			while( $threadId > 0 ) {
				$info = DomSql::selectOneQuery('SELECT thread, id, name FROM '.ForumThread::getTableName().' WHERE id = '.(int)$threadId.' LIMIT 1');
				$threadId = $info['thread'];
				$list[] = $info;
			}
			$view->list = array_reverse($list);
		}
		return $view->fetch();
	}
	
	
	public function otsing() {
		
		$this->view->addPartitioner('contents','Forum/search.html');
		
		if( $_POST['search']) {
		
			if( $_POST['userPosts'] ) {
				$search = '(user IN (SELECT id FROM users WHERE username LIKE \'%'.addslashes($_POST['searchWord']).'%\' or nickname LIKE \'%'.addslashes($_POST['searchWord']).'%\'))';	
			} else {
				$search = '(t.title LIKE \'%'.addslashes($_POST['searchWord']).'%\' or t.contents LIKE \'%'.addslashes($_POST['searchWord']).'%\')';
			}
			
			if( $_POST['thread'] ) {
				$search .= ' AND t.thread = '.(int)$_POST['thread'];
			}
			
			$result = DomSql::selectQuery('
					SELECT t.id, t.title, DATE_FORMAT(t.lastPostTime,\'%d-%m-%Y\') as lastPostTime, DATE_FORMAT(t.time,\'%d-%m-%Y\') as date
					FROM '.ForumTopic::getDbTable().' as t
					WHERE '.$search.'
					ORDER BY t.lastPostTime DESC
					LIMIT 25');
			
		
			/*$result = DomSql::selectQuery('
				SELECT t.id, t.title, DATE_FORMAT(p.time,\'%d-%m-%Y\') as date, DATE_FORMAT(t.time,\'%d-%m-%Y\') as topicDate
				FROM '.ForumPost::getDbTable().' as p
				LEFT JOIN '.ForumTopic::getDbTable().' as t ON (p.topic = t.id)
				WHERE 
					p.title LIKE \'%'.addslashes($_POST['searchWord']).'%\' or p.contents LIKE \'%'.addslashes($_POST['searchWord']).'%\' 
				ORDER BY p.time DESC
				GROUP BY t.id
				LIMIT 50
			')->toArray();
			*/
			
			$this->view->result = $result;
		
		}
		$this->view->assign( $_POST );
	
		$this->view->threads = ForumThread::getTree('Kõikide');
	}
	
	public function staarid() {
		
		$users = BuduaarUser::dataQuery()->select('t.id, t.nickname, t.posts')->orderBy('t.posts DESC')->limit(150)->commit()->toArray();
		$this->view->users = $users;
		
		$this->view->addPartitioner('contents','Forum/stars.html');
		$this->view->title = 'Buduaari foorumi staarid';
		$this->view->description = 'Buduaari foorumi staarid';
		$this->view->keywords = 'Buduaar, Foorum, Staarid, Populaarsed';
	
	}
	
	public function viimased() {
		
		$view = new DomView('Forum/latestTopics.html',20,'forumLatestTopics');
		
		if( !$view->isCached() ) {
			$threads = array();
			$request = ForumThread::dataQuery()->select('t.id, t.name')->where('t.thread <=> NULL')->commit();
			foreach( $request as $thread ) {
				$thread['topics'] = ForumTopic::dataQuery()
					->select('t.id, t.title, t.lastPostTime, t.icon, t.views, t.nrOfPosts, t.lastPostUserNickname, u.username as starterUsername')
					->where('t.className = \'ForumTopic\' AND t.thread IN (SELECT id FROM forum_threads WHERE thread = '.(int)$thread['id'].')')
					->join('users','u','u.id = t.user')
					->orderBy('t.lastPostTime DESC')
					->limit(10)
					->commit()->toArray();
					
				foreach( $thread['topics'] as &$topic ) {
					$topic['lk'] = ceil($topic['nrOfPosts']/40)-1;
					$topic['lk'] = $topic['lk'] < 0 ? 0 : $topic['lk'];
				}	
				
				$threads[] = $thread;
			}
			$view->threads = $threads;
		}
		$this->view->contents = $view->fetch();
		$this->view->title = 'Buduaari foorumi viimased teemad';
		$this->view->description = 'Buduaari foorumi viimased teemad';
		$this->view->keywords = 'Buduaar, Foorum, Viimased teemad, Uued teemad';
	
	}
	

	public function setup() {
		
	}
	
	public function finalize() {
		
	}
	
	public function error404() {
		$this->view->addPartitioner('contents', '/Buduaar/Errors/error404.html');
	}

}
?>